#########################################################################################
# Title: Figure2.R
# Author: Yuki Atsusaka (atsusaka@rice.edu)
# Aim: Code to replicate Figure 2 in Atsusaka (2021)
#########################################################################################

# CLEAN THE GLOBAL ENVIRONMENT AND READ PACKAGES
rm(list=ls())
library(viridis)

pdf(here::here("Atsusaka_Figure2.pdf"), width=8, height=4.2) # Open a pdf file
par(mfrow=c(1,2), mar=c(5,2,2,1), oma=c(0,2,0,0))

##############################################################
# PANEL A
##############################################################

MC.sqrt.min50 <- seq(from=-50,to=50,by=0.1) # Values in the model's parameter space
P1 <- pnorm(MC.sqrt.min50, mean=0,sd=1)     # Vector of model predictions
c1 <- "maroon"                              # Setting line color

plot(0, type="n", xaxt="n", ylim=c(0,1),xlim=c(-50,50),
     ylab="", xlab=expression((MC)^{1/2}-50))
axis(1, at = seq(-50, 50, by=25), las=1)
lines(P1 ~ MC.sqrt.min50, col=c1, lty=1, lwd=4)
abline(v=0,lty=2,col="dimgray", lwd=2)
text(x=25, y=0.45, cex=1, font=2, col="dimgray",
     labels=expression(widehat(V)[t]^{M} - widehat(V)[t]^{W} > 0))
text(x=-25, y=0.45, cex=1, font=2, col="dimgray",
     labels=expression(widehat(V)[t]^{M} - widehat(V)[t]^{W} < 0))
text(x=25,  y=0.55, cex=1, font=1, col="dimgray", labels="Expect to Win")
text(x=-25, y=0.55, cex=1, font=1, col="dimgray", labels="Expect to Lose")
mtext("Pr(Minority Candidate Emergence)", side=2, line=2.1, cex=1)
title("A", adj=0)

##############################################################
# Panel B
##############################################################

M = seq(from=0, to=100, by=1) # Vector of the racial margin of victory
gr <- rev(magma(10))          # Setting line colors


plot(0, type="n", xaxt="n", ylim=c(0,1),xlim=c(0,100),
     ylab="",xlab="M (Racial Margin of Victory)", cex.lab=1.2)
axis(1, at = seq(0, 100, by=25), las=1)


for(i in 1:10){                              
  C = i * 10                                 # Varying % Minority Voters (= C)
  MC.sqrt.min50 = sqrt(M*C) - 50             # Model prediction
  P  <- pnorm(MC.sqrt.min50, mean=0, sd=1)   # Draw a curve with a different color 
  lines(P ~ M, col=gr[i],lwd=4)
}         

text(90,0.06, labels="C=20", font=2)
text(88,0.9, labels="C=30", font=2)
text(68,0.9, labels="C=40", font=2)
text(52,0.9, labels="C=50", font=2)
text(14,0.9, labels="C=100",font=2)
title("B", adj=0)

dev.off() # Close the Pdf File

#########################################################################################
# END OF THIS R SOURCE FILE
#########################################################################################